package MapReduce.Demo11_ProductSerch;

import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;
import utils.JobSubmit;

import java.io.IOException;

/**
 * @Author lixinlei
 * @Date 2023/3/22 11:11
 */
public class ProductSearchCountEasyApp {

    public static class PSCEMapper extends Mapper<LongWritable, Text,Text,Text>{

        Text outKey = new Text();
        Text outValue = new Text("1");

        @Override
        protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, Text, Text>.Context context) throws IOException, InterruptedException {

            FileSplit fileSplit = (FileSplit) context.getInputSplit();
            String fileName = fileSplit.getPath().getName();

            String line = value.toString();
            String[] products = line.split(" ");

            for (String product : products) {
                outKey.set(product+"#"+fileName);
                context.write(outKey,outValue);
            }

        }
    }

    public static class PSCEReducer extends Reducer<Text,Text,Text,Text>{

        Text outValue = new Text();

        @Override
        protected void reduce(Text key, Iterable<Text> values, Reducer<Text, Text, Text, Text>.Context context) throws IOException, InterruptedException {

            StringBuffer sb = new StringBuffer();
            for (Text value : values) {
                sb.append(value.toString()+",");
            }

            String platform = sb.toString();
            platform = platform.substring(0,platform.lastIndexOf(","));
            platform = platform.replace(".txt","");

            outValue.set(platform);
            context.write(key,outValue);
        }
    }

    public static void main(String[] args) {
        JobSubmit.submitBaseJob(
                ProductSearchCountEasyApp.class,
                args,
                ProductSearchCountEasyCombiner.class
        );
    }
}
